package com.service.test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.quartz.Scheduler;
import org.quartz.SchedulerException;

import com.service.bean.company.Company;
import com.service.bean.device.Vehicle;
import com.service.cache.CacheManager;
import com.service.db.DbConnectionManager;
import com.service.db.PooledConnection;
import com.service.other.Logger;
import com.service.scheduler.sched.SaveGpsSched;
import com.service.scheduler.sched.SaveWorkChangeSched;
import com.service.socket.process.R_Class_E2;
import com.service.socket.protocol.Conversion;
import com.service.socket.protocol.Packet;
import com.service.socket.protocol.Resolver;

/****
 * 拌合楼补数据工具
 * （1）参数 del 20160601 20160630
 *     意思是 删除20160601~20160630的数据
 *     处理内容：删除 crc_GPSSignal，crc_GPSSignalWork的数据
 * （2）参数 add 20160601 20160630
 *     意思是 补20160601~20160630的数据
 * 	   数据默认路径在当前包的gpsdata目录下。
 * 		处理内容：以车为单位，全部处理一遍。
 * 
 * 
 * @author Administrator
 *
 */
public class DataRebornMix {


	public static String flag = null;
	public static String from_date = null;
	public static String end_date = null;
	public static String deleteby = null;
	
	/**
	 * 注意：
	 * ScalarCal 		出勤报表，报警逻辑，加油逻辑注释掉。
	 * Road_ScalarCal 	不用改
	 * R_Class_B0		去掉一些异常日志。
	 * 
	 * @param args
	 */
	public static void main(String[] args) {

		
		flag = "add";
		from_date = "20161121";
		end_date = "20161203";
		deleteby = "1";

		System.out.println(flag + " start " + from_date + " to " + end_date + " deleteby: "+deleteby);
		if("del".equals(flag)){
			//删除数据
			delData(from_date,end_date,deleteby);
		}else if("add".equals(flag)){
			//补数据
			
			Thread t = new Thread(){
				 @Override
				 public void run() {
					 addData(from_date,end_date);
				 }
			};
			t.start();
			
		}

	}
	
	
	public static List<Company> getAllCompany() {
		//获得所有的公司，然后删除指定日期内所有的数据
		List<Company> listcompany = new ArrayList<>();
		//环卫所有的车
		for (Vehicle vehicle : CacheManager.instance().vehicleMap.values()) {
			if(!listcompany.contains(vehicle.company)){
				listcompany.add(vehicle.company);
			}
		}

		
		return listcompany;
	}
	
	public static void delData(String from_date,String end_date,String deleteby) {
		if("1".equals(deleteby)){
			System.out.println("<<<< 1111111111111111 >>>>");
			List<Company> listcompany = getAllCompany();
			for(Company company:listcompany){
				if(!"001".equals(company.code)){
					continue;
				}
				System.out.println(company.code+" <<<< delete start >>>>");
				deleteData1(company,from_date,end_date,null);
			}
		}
		System.out.println("<<<< delete all end ! >>>>");
	}



	public static void addData(String from_date,String end_date) {

		String filepath = null;
		//缓存初始化
		CacheManager.instance();	
		
		String from_date_tmp = from_date;
		
		try {
			File directory = new File("");//参数为空 
			filepath = directory.getCanonicalPath() + "\\gpsdata";
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 

		//启动定时器
		intanceScheduler();
		int i=0;
		//环卫所有的车
		if (!CacheManager.instance().roadMixingMap.isEmpty()) {
			i=i+1;
			from_date_tmp = from_date;
			while (!from_date_tmp.equals(end_date)) {
				
				readFile(filepath + "\\" + changeDate(from_date_tmp) + "\\00000000000.txt", from_date_tmp);
				from_date_tmp = nextDay(from_date_tmp);
			}
			
			//等当前车处理完毕，数据存储完毕，再处理下一辆车
			while (true) {
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}

		}
		
	}
	
	
	/**
	 * 日期格式转换
	 */
	public static String changeDate(String time) {
		String dateString = null;
		SimpleDateFormat df=new SimpleDateFormat("yyyyMMdd");
		Date date = null;
		try {
			date = df.parse(time);
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
			dateString = formatter.format(date);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return dateString;
	}
	

	private static void intanceScheduler() {
		new SaveGpsSched().init();
		for (Scheduler sched : CacheManager.instance().schedMap.values()) {
			try {
				sched.start();
			} catch (SchedulerException e) {
				Logger.err(e);
			}
		}
	}

	/**
	 * 返回传入参数的下一天
	 */
	public static String nextDay(String time) {
		Calendar cal = Calendar.getInstance();
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
		Date date = null;
		try {
			date = df.parse(time);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		cal.setTime(date);
		cal.add(Calendar.DATE, 1);

		return df.format(cal.getTime());
	}

	/**
	 * 返回传入参数的前一一天
	 */
	public static String preDay(String time) {
		Calendar cal = Calendar.getInstance();
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
		Date date = null;
		try {
			date = df.parse(time);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		cal.setTime(date);
		cal.add(Calendar.DATE, -1);

		return df.format(cal.getTime());
	}

	public static void readFile(String filePath, String date) {
		try {
			String encoding = "GBK";
			Packet packet = null;
			
			File file = new File(filePath);
			boolean ifNextreceive = false;
			if (file.isFile() && file.exists()) { // 判断文件是否存在
				InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);// 考虑到编码格式
				BufferedReader bufferedReader = new BufferedReader(read);
				String lineTxt = null;
				while ((lineTxt = bufferedReader.readLine()) != null) {
					
					if (lineTxt.startsWith("receive")) {
						ifNextreceive = true;
						continue;
					}
					
					
					// 解析packet
					String s = lineTxt.substring(2, lineTxt.length() - 2);
					byte[] bytes = Conversion.dataEncode(Conversion.hexStringToBytes(s.toString()));
					packet = Resolver.parsePacket(bytes);
					if (packet != null && packet.cmdType.equals("E2") && ifNextreceive) {
						new R_Class_E2(null, packet).execute();
						ifNextreceive = false;
					}
				}
				read.close();
			} else {
//				System.out.println("找不到指定的文件");
			}
		} catch (Exception e) {
			System.out.println("读取文件内容出错");
			e.printStackTrace();
		}

	}

	/**
	 * 批量保存GpsSignalWorkSpeed对象
	 */
	private static void deleteData1(Company company,String staTime,String endTime,String equipmentId) {

		PooledConnection con = null;
		PreparedStatement pstmt = null;
		try {

			con = DbConnectionManager.getConnection(company);

			String sql = "delete from road_MixingSignal where convert(VARCHAR(10),[MixingTime],112) >= ? and convert(VARCHAR(10),[MixingTime],112) <= ?";

			if(equipmentId != null){
				sql = sql +" and EquipmentId=? ";
			}
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, staTime);
			pstmt.setString(2, endTime);
			if(equipmentId != null){
				pstmt.setString(3, equipmentId);
			}
			pstmt.execute();
		} catch (SQLException e) {
			Logger.err(e);
		} finally {
			try {
				if(pstmt!=null && !pstmt.isClosed()){
					pstmt.close();
				}
				if (con != null) {
					con.close();
				}
			} catch (SQLException e) {
				Logger.err(e);
			}
		}
	}
	
}
